package com.wfaces.mb;

import com.wfaces.dao.Dao;
import com.wfaces.entities.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.apache.log4j.Logger;

/**
 *
 * @author lhoussin
 */
@ManagedBean(name = "searchMB")
@SessionScoped
public class SearchMB implements Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * Creates a new instance of SearchMB
     */
    private String searchFor;
    private List<User> foundUsers;
    private List<User> selectedUsers = new ArrayList<User>();
    private static final Logger logger = Logger.getLogger(ChatMB.class.getName());
    private User advUser;

    public SearchMB() {
    }

    public String search() {
        logger.info("searching for : " + searchFor);
        foundUsers = Dao.searchForUsers(searchFor);
        foundUsers.removeAll(selectedUsers);
        return "";
    }

    public String select(User user) {
        int index = foundUsers.indexOf(user);
        logger.info("index of the user :" + index);
        logger.info("avant : " + foundUsers.size());
        User lastUser = foundUsers.get(foundUsers.size() - 1);
        foundUsers.set(index, lastUser);
        logger.info("après : " + foundUsers.size());
        selectedUsers.add(user);
        foundUsers.remove(foundUsers.size() - 1);
        logger.info("après après :" + foundUsers.size());
        if (selectedUsers.size() == 16) {
            return "chat";
        }
        return "";
    }

    public String getSearchFor() {
        return searchFor;
    }

    public void setSearchFor(String searchFor) {
        this.searchFor = searchFor;
    }

    public List<User> getFoundUsers() {
        return foundUsers;
    }

    public void setFoundUsers(List<User> foundUsers) {
        this.foundUsers = foundUsers;
    }

    public List<User> getSelectedUsers() {
        return selectedUsers;
    }

    public void setSelectedUsers(List<User> selectedUsers) {
        this.selectedUsers = selectedUsers;
    }

    public User getAdvUser() {
        if (selectedUsers.size() > 0) {
            return selectedUsers.get(0);
        }
        return advUser;
    }

}